package top.shiyiri.spring5;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

/**
 * @author Aunean
 * @date 2022/2/17 18:12
 */
public class JDKProxy {

    public static void main(String[] args) {

        UserDao userDao = new UserDaoImpl();
        Class[] interfaces = {UserDao.class};
        //创建接口实现类代理对象
        UserDao dao = (UserDao) Proxy.newProxyInstance(JDKProxy.class.getClassLoader(),
                interfaces, new UserDaoProxy(userDao));

        int result = dao.add(1, 34);
        System.out.println(result);
    }
}


//创建代理对象代码
class UserDaoProxy implements InvocationHandler {

    //把创建是谁的代理对象，把谁传递过来
    private Object object;
    public UserDaoProxy(Object object) {
        this.object = object;
    }

    //增加的逻辑
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        //方法之前
        System.out.println("方法之前执行..." + method.getName() + ":传递的参数..." + Arrays.toString(args));
        //被增强的方法执行
        Object invoke = method.invoke(object, args);
        //方法之后
        System.out.println("方法之后执行..." + object);
        return invoke;
    }
}